var LangMgmt = function(obj, opts) {
  this.__obj = obj;
  this.__date = (opts && opts.date) ? opts.date : {};
  this.__student = (opts && opts.student) ? opts.student : {};
  this.__pdenrls = (opts && opts.pdenrls) ? opts.pdenrls : [];
  this.__enrlclasses = (opts && opts.enrlclasses) ? opts.enrlclasses : [];
  this.__enrlintakes = (opts && opts.enrlintakes) ? opts.enrlintakes : [];
  this.__courses = (opts && opts.courses) ? opts.courses : [];
  this.__update_nav = (opts && opts.update_nav) ? opts.update_nav : function(id, eit_id) {};
  this.__readonly = (opts && opts.readonly == 1) ? opts.readonly : 0;
  this.__new_eits = [];
  this.__intakes = [];
  this.__classes = [];
  
  this.create_extra();
};

LangMgmt.prototype.create = function() {
  var self = this;
  
  $('#ep_content').empty();
  if (this.__readonly == 0) {
    $('#ep_content').append('<button class="pure-button pure-button-primary" onclick="__lang_m.dialog_open();">Add...</button>');
  }
  $('#ep_content').append(
    '<table style="width: 650px;" class="pure-table pure_table_academic" cellpadding=0 cellspacing=0>' +
      '<thead>' +
        '<tr>' +
          '<th style="width: 40px;">&nbsp;</th>' +
          '<th style="width: 80px;">Start</th>' +
          '<th style="width: 80px;">End</th>' +
          '<th>Classes</th>' +
          '<th style="width: 40px;">&nbsp;</th>' +
        '</tr>' +
      '</thead>' +
      '<tbody id="eit_body"></tbody>' +
    '</table>'
  );
  
  for (var idx in this.__obj.__enrlintakes) {
    var itm = this.__obj.__enrlintakes[idx];
    var sts = Utils.date_to_status(itm.start, itm.end, this.__date);
    if (sts == 1) {
      sts = '<b style="color: #e87352;">Now</b>';
    } else if (sts == 0) {
      sts = '<b style="color: #000;">Past</b>';
    } else if (sts == 2) {
      sts = '<b style="color: #ff00ff;">Coming</b>';
    } else {
      sts = '';
    }
    $('#eit_body').append(
      '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
        '<td>' + sts + '</td>' +
        '<td><input' + ((this.__readonly == 1) ? ' disabled="disabled"' : '') + ' id="eit_s_' + itm.id + '" value="' + itm.start + '"/></td>' +
        '<td><input' + ((this.__readonly == 1) ? ' disabled="disabled"' : '') + ' id="eit_e_' + itm.id + '" value="' + itm.end + '"/></td>' +
        '<td>' + this.get_clnames(itm) + '</td>' +
        '<td>' +
          '<i class="fa fa-pencil" onclick="__lang_m.create_eit(' + itm.id + ');"></i>&nbsp;' +
          ((this.__readonly == 0) ? '<i class="fa fa-times" onclick="__lang_m.del_eit(' + itm.id + ');"></i>' : '') +
        '</td>' +
      '</tr>'
    );
    
    $('#eit_s_' + itm.id).datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      showButtonPanel: true,
      onSelect: function(dateText) {
        req = Utils.get_by_id(this.id.replace('eit_s_', ''), self.__obj.__enrlintakes);
        req.start = dateText;
        Ajax.request(
          __requrl + 'submit_enrl_intakes',
          'req=' + Utils.encodeURI(JSON.stringify([ req ])),
          function(rslt) {
            var obj = Utils.get_by_id(req.id, self.__enrlintakes);
            obj.start = dateText;
            self.create.call(self);
          },
          null
        );
      }
    });
    
    $('#eit_e_' + itm.id).datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      showButtonPanel: true,
      onSelect: function(dateText) {
        req = Utils.get_by_id(this.id.replace('eit_e_', ''), self.__obj.__enrlintakes);
        req.end = dateText;
        Ajax.request(
          __requrl + 'submit_enrl_intakes',
          'req=' + Utils.encodeURI(JSON.stringify([ req ])),
          function(rslt) {
            var obj = Utils.get_by_id(req.id, self.__enrlintakes);
            obj.end = dateText;
            self.create.call(self);
          },
          null
        );
      }
    });
  }
  
  if (this.__obj.__enrlintakes.length == 0) {
    $('#eit_body').append('<tr class="pure-table-even"><td colspan=8>None</td></tr>');
  }
  
  this.__update_nav(this.__obj.id, -1);
};

LangMgmt.prototype.get_clnames = function(obj) {
  var str = '';
  for (var idx in obj.__enrlclasses) {
    var itm = obj.__enrlclasses[idx];
    str += ((str != '') ? ', ' : '') + itm.class_name;
  }
  return str;
};

LangMgmt.prototype.create_eit = function(id) {
  this.__update_nav(this.__obj.id, id);

  var self = this;
  
  var obj = Utils.get_by_id(id, this.__obj.__enrlintakes);
  var req = {};
  Ajax.request(
    __requrl + 'get_lang_classes',
    'req=' + Utils.encodeURI(JSON.stringify(req)),
    function(rslt) {
      self.__classes = rslt;
      self.setup_eit.call(self, id);
    },
    null
  );
};

LangMgmt.prototype.del_eit = function(id) {
  var self = this;
  
  var req = {
    id: id
  }

  Ajax.request(
    __requrl + 'delete_enrl_intake',
    'req=' + Utils.encodeURI(JSON.stringify(req)),
    function(rslt) {
      Utils.splice_by_id(id, self.__enrlintakes);
      Utils.splice_by_id(id, self.__obj.__enrlintakes);
      self.__update_nav(self.__obj.id, -1);
      self.create.call(self);
    },
    { confirm: 1 }
  );
};

LangMgmt.prototype.setup_eit = function(id) {
  var obj = Utils.get_by_id(id, this.__obj.__enrlintakes);
  
  $('#ep_content').empty();
  $('#ep_content').append('<div id="alleits" style="padding: 10px 20px; width: 650px;" class="ui-state-highlight ui-corner-all"></div>');
  $('#alleits').append('<button class="pure-button pure-button-back" style="margin-right: 5px;" onclick="__lang_m.create()"><i class="fa fa-arrow-circle-left"></i>&nbsp;Back</button>');

  for (var idx in this.__obj.__enrlintakes) {
    var itm = this.__obj.__enrlintakes[idx];
    $('#alleits').append('<button class="pure-button' + ((itm.id == id) ? ' pure-button-intake' : '') + '" style="margin-right: 5px;" onclick="__lang_m.create_eit(' + itm.id + ')">' + itm.start + ' to ' + itm.end + '</button>');
  }
  
  $('#ep_content').append(
    '<div>&nbsp;</div>' +
    '<div class="pure-form">' +
      '<legend><h3>' + obj.start + ' to ' + obj.end + '</h3></legend>' +
     
      '<fieldset class="pure-group">' +
        '<input' + ((this.__readonly == 1) ? ' disabled="disabled"' : '') + ' id="eit_vw" type="text" class="pure-input-1-2" placeholder="Verbal Warning" value="' + ((obj.w1 == '0000-00-00') ? '' : obj.w1) + '"/>' +
        '<input' + ((this.__readonly == 1) ? ' disabled="disabled"' : '') + ' id="eit_1st" type="text" class="pure-input-1-2" placeholder="1st Warning" value="' + ((obj.w2 == '0000-00-00') ? '' : obj.w2) + '"/>' +
        '<input' + ((this.__readonly == 1) ? ' disabled="disabled"' : '') + ' id="eit_2nd" type="text" class="pure-input-1-2" placeholder="2nd Warning" value="' + ((obj.w3 == '0000-00-00') ? '' : obj.w3) + '"/>' +
        '<textarea id="eit_note" style="resize: none;" class="pure-input-1-2" placeholder="Note">' + (obj.note ? obj.note : '') + '</textarea>' +
      '</fieldset>' +
      '<button class="pure-button pure-input-1-2 pure-button-primary" onclick="__lang_m.save_eit(' + id + ');">Save</button>' +
    '<div>' + 
    '<div>&nbsp;</div>' +
    '<div id="eit_classes"></div>'
  );
  
  $('#eit_vw').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm-dd",
    showButtonPanel: true
  });
  $('#eit_1st').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm-dd",
    showButtonPanel: true
  });
  $('#eit_2nd').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm-dd",
    showButtonPanel: true
  });
  
  this.create_eit_classes(id);
};

LangMgmt.prototype.create_eit_classes = function(id) {
  var self = this;
  
  $('#eit_classes').empty();
  $('#eit_classes').append(
    '<table class="pure-table pure_table_academic" cellpadding=0 cellspacing=0>' +
      '<thead>' +
        '<tr>' +
          '<th>Class</th>' +
          '<th style="width: 60px;">Atdn</th>' +
        '</tr>' +
      '</thead>' +
      '<tbody id="ecl_body"></tbody>' +
    '</table>'
  );
  
  var obj = Utils.get_by_id(id, this.__obj.__enrlintakes);
  for (var idx in obj.__enrlclasses) {
    var itm = obj.__enrlclasses[idx];
    $('#ecl_body').append(
      '<tr class="' + ((idx % 2 == 1) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
        '<td><select' + ((itm.__atdn != -1 || this.__readonly == 1) ? ' disabled="disabled"' : '') + ' style="width: 100%;" id="ecl_ecl_' + itm.id + '" onchange="__lang_m.update_ecl(' + itm.id + ', ' + id + ');"><option value="0">&nbsp;</option></select></td>' +
        '<td>' + itm.__atdn + '%</td>' +
      '</tr>'
    );
    $('#ecl_ecl_sts_' + itm.id).val(itm.status);
    for (var idx2 in this.__classes) {
      var itm2 = this.__classes[idx2];
      var exist = 0;
      if (itm.class_id != itm2.id) {
        for (var idx3 in obj.__enrlclasses) {
          var itm3 = obj.__enrlclasses[idx3];
          if (itm3.class_id == itm2.id) {
            exist = 1;
          }
        }
      }
      if (exist == 0) {
        $('#ecl_ecl_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.class_id) ? ' selected="selected"' : '') + '>' + itm2.course_name + ' ' + itm2.name + '</option>');
      }
    }
  }

  if (this.__readonly == 0) {
    for (var i = obj.papers, il = -1; i > il; i--) {
      $('#ecl_body').append(
        '<tr class="' + ((i % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td><select style="width: 100%;" id="ecl_cl_' + i + '" onchange="__lang_m.add_ecl(' + i + ', ' + id + ');"><option value="0">&nbsp;</option></select></td>' +
          '<td></td>' +
        '</tr>'
      );
      for (var idx in this.__classes) {
        var itm = this.__classes[idx];
        var exist = 0;
        for (var idx2 in obj.__enrlclasses) {
          var itm2 = obj.__enrlclasses[idx2];
          if (itm.id == itm2.class_id) {
            exist = 1;
          }
        }
        if (exist == 0) {
          $('#ecl_cl_' + i).append('<option value="' + itm.id + '">' + itm.course_name + ' ' + itm.name + '</option>');
        }
      }
    }
  }
  
  $('#eit_classes').append(
    '<div>&nbsp;</div>' +
    '<div class="pure-button pure-button-pass" style="margin-bottom: 5px;" onclick="window.open(\'____tb.php?id=' + id + '\')">Print Timetable</div>' +
    '<div id="timetable"></div>'
  );
  
  $('#timetable').empty();
  $('#timetable').fullCalendar({
    defaultView: 'agendaWeek',
    header: {
      left: '',
      center: '',
      right: ''
    },
    columnFormat: {
      week: 'ddd'
    },
    year: 2000,
    month: 0,
    date: 3,
    allDaySlot: false,
    height: 800,
    weekends: false,
    theme: true,
    
    minTime: 8,
    maxTime: 23,
    
    timeFormat: 'HH:mm{-HH:mm}',

    editable: false,
    selectable: false,

    events: function(start, end, callback) {
      var obj = Utils.get_by_id(id, self.__obj.__enrlintakes);
      for(var idx in obj.__enrlclasses) {
        var itm = obj.__enrlclasses[idx];
        if (itm.status == 3) {
          continue;
        }
        for (var idx2 in JSON.parse(itm.__times)) {
          var itm2 = JSON.parse(itm.__times)[idx2];
          var rslt = itm2.split('-');
          var cl = Utils.get_by_id(itm.class_id, self.__classes);
          for (var i = 3; i < 8; i++) {
            var evt = {
              start: '2000-01-0' + i + ' ' + rslt[0] + ':00',
              end: '2000-01-0' + i + ' ' + rslt[1] + ':00',
              allDay: 0,
              title: itm.class_name + ((cl.room_id != 0) ? '\n' + cl.room_name : '') + ((cl.teacher_id != 0) ? '\n' + cl.teacher_name : ''),
              description: ''
            };
            $("#timetable").fullCalendar('renderEvent', evt, true);
          }
        }
      }
    }
  });
  
};

LangMgmt.prototype.update_ecl = function(ecl_id, eit_id) {
  var self = this;
  
  var cl = Utils.get_by_id($('#ecl_ecl_' + ecl_id + ' :selected').val(), this.__classes);
  var eit = Utils.get_by_id(eit_id, this.__obj.__enrlintakes);
  var ecl = Utils.get_by_id(ecl_id, eit.__enrlclasses);
  var ecl2 = Utils.get_by_id(ecl_id, this.__enrlclasses);
  
  if (!cl) {
    
    Ajax.request(
      __requrl + 'delete_enrl_class',
      'req=' + Utils.encodeURI(JSON.stringify(ecl)),
      function(rslt) {
        Utils.splice_by_id(ecl_id, this.__enrlclasses);
        Utils.splice_by_id(ecl_id, eit.__enrlclasses);
        self.create_eit_classes.call(self, eit_id);
        self.create_extra.call(self);
      },
      null
    );
  } else {
    ecl.class_id = cl.id;
    ecl.class_name = cl.name;
    ecl.course_id = cl.course_id;
    ecl.course_name = cl.course_name;
    ecl.__times = cl.times;
    ecl2.class_id = cl.id;
    ecl2.class_name = cl.name;
    ecl2.course_id = cl.course_id;
    ecl2.course_name = cl.course_name;
    ecl2.__times = cl.times;
    Ajax.request(
      __requrl + 'submit_enrl_class',
      'req=' + Utils.encodeURI(JSON.stringify(ecl)),
      function(rslt) {
        self.create_eit_classes.call(self, eit_id);
        self.create_extra.call(self);
      },
      null
    );
  }
};

LangMgmt.prototype.add_ecl = function(idx, id) {
  var self = this;
  
  var obj = Utils.get_by_id($('#ecl_cl_' + idx + ' :selected').val(), this.__classes);
  var obj2 = Utils.get_by_id(id, this.__obj.__enrlintakes);
  var req = {
    type__: obj.type,
    type_ncea__: obj2.type_ncea__,
    enrollment_id: obj2.enrollment_id,
    enrolled_program_id: obj2.enrolled_program_id,
    enrolled_intake_id: id,
    intake_id: 0,
    class_id: obj.id,
    class_name: obj.name,
    course_id: obj.course_id,
    course_name: obj.course_name,
    student_id: this.__student.id,
    start: obj2.start,
    end: obj2.end,
    status: 0,
    result__: -2,
    __times: obj.times,
    __atdn: -1
  };
  Ajax.request(
    __requrl + 'submit_enrl_class',
    'req=' + Utils.encodeURI(JSON.stringify(req)),
    function(rslt) {
      self.__enrlclasses.push(rslt);
      var obj = Utils.get_by_id(id, self.__obj.__enrlintakes);
      obj.__enrlclasses.push(rslt);
      self.create_eit_classes.call(self, id);
      self.create_extra.call(self);
    },
    null
  );
};

LangMgmt.prototype.save_eit = function(id) {
  var self = this;
  
  var obj = Utils.get_by_id(id, this.__obj.__enrlintakes);
  obj.w1 = ($('#eit_vw').val() == '') ? '0000-00-00' : $('#eit_vw').val();
  obj.w2 = ($('#eit_1st').val() == '') ? '0000-00-00' : $('#eit_1st').val();
  obj.w3 = ($('#eit_2nd').val() == '') ? '0000-00-00' : $('#eit_2nd').val();
  obj.note = $('#eit_note').val();
  Ajax.request(
    __requrl + 'submit_enrl_intakes',
    'req=' + Utils.encodeURI(JSON.stringify([ obj ])),
    function(rslt) {
      self.create_eit_classes.call(self, id);
    },
    null
  );
};

LangMgmt.prototype.dialog_open = function() {
  this.dialog_setup();
};

LangMgmt.prototype.dialog_setup = function() {
  var self = this;
  
  var func = function() {
    var obj = {
      type__: '',
      enrollment_id: self.__enrlintakes[0].enrollment_id,
      enrolled_program_id: self.__obj.id,
      student_id: self.__student.id,
      intake_id: 0,
      start: $('#eit_ns').val(),
      end: $('#eit_ne').val(),
      papers: 0,
      w1: '0000-00-00',
      w2: '0000-00-00',
      w3: '0000-00-00',
      note: '',
      __enrlclasses: []
    };
    var req = [ obj ];
    for (var idx in self.__obj.__enrlintakes) {
      var itm = self.__obj.__enrlintakes[idx];
      if (Utils.date_to_status(obj.start, obj.end, itm.end) == 1) {
        itm.end = Utils.shift_earlier(obj.start, 3);
        req.push(itm);
      }
    }
    for (var idx in self.__enrlintakes) {
      var itm = self.__enrlintakes[idx];
      if (itm.enrolled_program_id == self.__obj.id && Utils.date_to_status(obj.start, obj.end, itm.end) == 1) {
        itm.end = Utils.shift_earlier(obj.start, 3);
      }
    }
    
    Ajax.request(
      __requrl + 'submit_enrl_intakes',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        for (var idx in rslt) {
          var itm = rslt[idx];
          if (itm.start == obj.start && itm.end == obj.end) {
            self.__obj.__enrlintakes.splice(0, 0, itm);
            self.__enrlintakes.splice(0, 0, itm);
          }
        }
        self.create.call(self);
        $('#dialog_academic').dialog('close');
      },
      null
    );
  };
  
  $('#dialog_academic').dialog({
    width: 500,
    buttons: {
      'OK': function() {
        func();
      },
      'Cancel': function() { 
        $(this).dialog('close');
      }
    }
  });
  
  $('#dialog_academic').empty();
  $('#dialog_academic').append(
    '<div class="pure-form">' +
      '<b>New Classes Start From</b>&nbsp;<input id="eit_ns" type="text" value="' + Utils.next_monday(__date) + '" />&nbsp;<b>To</b>&nbsp;<input id="eit_ne" type="text" value="' + this.__obj.__end + '" />' +
    '</div>'
  );
  $('#eit_ns').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm-dd",
    showButtonPanel: true
  });
  $('#eit_ne').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm-dd",
    showButtonPanel: true
  });
};

LangMgmt.prototype.create_extra = function(obj) {
  $('#ep_extra').empty();

};
